<template>
  <view>

    <wait v-if="orderType === 'create'" ref="waitRef" />
    <pay :data="orderDetail" :tradeId="tradeId" v-if="orderType == 'pay'" ref="payRef" />
    <comfirm :data="orderDetail" v-if="orderType == 'info'" />
    <afterSale :data="orderDetail" v-if="orderType == 'afterSale'" ref="afterSaleRef" />

    <view style="height: 80px;"></view>

    <view
      class="flex-block p-10"
      style="position: fixed; bottom: 0; left: 0; z-index: 999; background-color: #ffffff; width: 100%; box-sizing: border-box;"
      >
      <view style="flex: 1" v-if="orderType == 'create'">
        <up-button size="normal" :color="$u.color.mainColor" @click="submit">创建订单</up-button>
      </view>
      
      <template v-if="orderDetail.trade">
        <view style="flex: 1" v-if="orderDetail.trade.status.value == 20 || orderDetail.trade.status.value == 30">
          <up-button size="normal" type="info" @click="orderCancel">取消订单</up-button>
        </view>
        <template v-if="orderDetail.trade.status.value == 10">
          <view style="flex: 1">
            <view>
              <up-button size="normal" :color="$u.color.mainColor" @click="toPay" v-if="ifPay">
                去支付
              </up-button>
              <up-button size="normal" :color="$u.color.mainColor" v-else>
                {{ payThreshold.description }}
              </up-button>
            </view>
          </view>
        </template>
        <template v-if="orderType == 'afterSale'">
          <view style="flex: 1">
            <up-button size="normal" :color="$u.color.mainColor" @click="saleApply">提交申请</up-button>
          </view>
        </template>
        <template v-if="orderDetail.trade.status.value == 40 && orderType != 'afterSale'">
          <view style="flex: 1">
            <up-button size="normal" :color="$u.color.mainColor" @click="finishOrder">确认收货</up-button>
          </view>
        </template>
      </template>
    </view>
  </view>
</template>

<script>
import wait from './wait.vue'
import pay from './pay.vue'
import comfirm from './comfirm.vue'
import afterSale from './afterSale.vue'
export default {
  components: { wait, pay, comfirm, afterSale },
  data() {
    return {
      orderType: '',
      tradeId: '',
      orderDetail: {},
      payThreshold: {}
    }
  },
  onLoad(options) {
    console.log(this.$u)
    this.tradeId = options.id || ''
    this.orderType = options.type || 'create'
    this.init()
    this.getExpressFee()
  },
  computed: {
    ifPay() {
      if (!this.$refs.payRef) return false

      // 活动订单不做起送金额判断
      if (this.orderDetail.trade.channel.value == 10) return true

      const totalPrice = this.$refs.payRef.payInfo.totalPrice
      if (totalPrice >= this.payThreshold.displayText) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    // 订单过滤状态 (0:已取消 10:待付款 20:待发货 30:待自提 40:待收货 50:已收货 60:待评价 70:已完成 80:售后中)
    enumStatus(status) {
      if (status == 10) {
        return 1
      } else if(!status) {
        return null
      } else {
        return 2
      }
    },
    init() {
      if (this.tradeId) {
        this.getOrderDetail()
      }
    },
    async submit() {
      let params
      if (this.$refs.waitRef.activeIndex == 1) {
        // 快递
        params = {
          "storeId": this.$refs.waitRef.model1.store.id,
          "addressId": this.$refs.waitRef.model1.address.id,
          "remark": this.$refs.waitRef.formData.remark,
          "delivery": this.$refs.waitRef.activeIndex,
          "expressFeeId": this.$refs.waitRef.model1.expressTime.id
        }
      } else {
        // 自提
        params = {
          "storeId": this.$refs.waitRef.model1.store.id,
          "remark": this.$refs.waitRef.formData.remark,
          "delivery": this.$refs.waitRef.activeIndex,
          "awayReserve": {
            phone: this.$refs.waitRef.model1.phone,
            bookTime: this.$refs.waitRef.model1.bookTime
          }
        }
      }
      let { code, data } = await this.$api.order.add(params)
      if (code == 200) {
        uni.showToast({
          title: '下单成功',
          icon: 'none'
        })
        this.$refs.waitRef.model1 = {
          addressStr: '',
          address: {},
          storeStr: '',
          store: {},
          expressInfo: {}
        }
        this.$refs.waitRef.formData.remark = ''

        this.tradeId = data.tradeId;
        this.orderType = 'pay';
        this.init()
      }
    },
    async getOrderDetail() {
      this.$api.order.detail({
        id: this.tradeId
      }).then(res => {
        this.orderDetail = res.data
      })
    },
    orderCancel() {
      uni.showModal({
        title: '提示',
        content: '确定取消订单吗？',
        success: (res) => {
          if (res.confirm) {
            this.$api.order.cancel({
              id: this.tradeId
            }).then(res => {
              uni.showToast({
                title: '取消成功',
                mask: true
              })
              uni.navigateBack({})
            })
          }
        }
      })
    },
    async toPay() {
      let status = await this.$refs.payRef.$refs.formRef.validate()
      if (!status) return;

      let payType
      if (uni.getSystemInfoSync().host && uni.getSystemInfoSync().host.env == 'WeChat') {
        payType = this.$refs.payRef.formData.patType
      } else if (uni.getSystemInfoSync().host === 'KUAISHOU') {
        payType = '4'
      }
      const {code, data} = await this.$api.order.pay({
        "id": this.tradeId,
        "payType": payType,
        "coin": this.$refs.payRef.formData.coin
      })

      if (code == 200) {
        if (payType != 4) {
          if (data.jsPay) {
            this.paysdk(data)
          } else {
            uni.navigateTo({ url: '/pages/pay-success/pay-success?id=' + data.id + '&type=order' })
          }
        } else {
          ks.pay({
              serviceId: '1',
              orderInfo: {
                order_no: data.payInfo.order_no,
                order_info_token: data.payInfo.order_info_token
              },
              success() {
                  // 支付成功
                  console.log("支付成功");
                  uni.navigateTo({ url: '/pages/pay-success/pay-success?id=' + data.id + '&type=order' })
              },
              fail() {
                  // 支付失败
              },
          });
        }
      }
    },
    paysdk(data) {
      uni.getProvider({
          service: 'payment',
          success: function (res) {
              console.log(res.provider)
              if (~res.provider.indexOf('wxpay')) {
                  uni.requestPayment({
                      provider: "wxpay",  //固定值为"wxpay"
                      ...data.jsPay,
                      orderInfo: data.jsPay,
                      success: function (res) {
                          // var rawdata = JSON.parse(res.rawdata);
                          console.log("支付成功");
                          uni.navigateTo({ url: '/pages/pay-success/pay-success?id=' + data.id + '&type=order' })
                      },
                      fail: function (err) {
                          console.log('支付失败:' + JSON.stringify(err));
                      }
                  });
              }
          }
      });
    },
    async finishOrder() {
      uni.showModal({
        title: '提示',
        content: '确定完成订单吗？',
        showCancel: true,
        success: async ({ confirm, cancel }) => {
          if (cancel) return
          const {code} = await this.$api.order.confirm({
            "id": this.tradeId
          })

          if (code == 200) {
            uni.showModal({
              title: '提示',
              content: '订单已完成',
              showCancel: false,
              success: (res) => {
                if (res.confirm) {
                  uni.navigateBack({})
                }
              }
            })
          } else {
            uni.showToast({
              title: '操作失败',
              icon: 'none'
            })
          }
        }
      })
    },
    saleApply() {
      this.$api.order.appeal({
        tradeId: this.tradeId,
        type: this.$refs.afterSaleRef.formData.type,
        reason: this.$refs.afterSaleRef.formData.reason,
        expressNo: this.$refs.afterSaleRef.formData.expressNo,
        photos: this.$refs.afterSaleRef.formData.photos,
      }).then(res => {
        uni.showToast({
          title: res.message,
          icon: 'success',
          mask: true
        })
        setTimeout(() => {
          uni.navigateBack({})
        }, 1000)
      })
    },
    // 订单金额起送额获取
    async getExpressFee() {
      const res = await this.$api.config.dict({
        code: 'PayThreshold'
      })
      console.log(res)
      this.payThreshold = res.data.details[0]
    },
  }
}
</script>

<style lang="stylus" scoped>
:deep(.u-form-item__body)
  padding 15px 0
</style>